import React, { useState, useEffect } from "react";
import { Keyboard, Alert } from "react-native";
import { router } from "expo-router";
import { LoginPropsType } from "@/types/login";

// 导入通用组件
import FormInput from "../components/FormInput";
import FormButton from "../components/FormButton";
import AgreementCheck from "../components/AgreementCheck";
import LoginContainer from "../components/LoginContainer";

// 导入自定义hooks
import { useLogin } from "@/hooks/Login/login-hook";
import {
  useFormValidation,
  validateEmail,
  validatePassword,
} from "@/hooks/Login/validate-hook";

const EmailLoginByPassword: React.FC<LoginPropsType> = ({ showAlert }) => {
  // 状态管理
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [showPassword, setShowPassword] = useState(false);
  const [agreed, setAgreed] = useState(false);

  // 使用自定义hooks
  const { errors, validateField, setErrors } = useFormValidation();
  const { isLoading, loginWithEmailPassword, getLastLoginCredentials } = useLogin();

  // 组件挂载时初始化验证状态
  useEffect(() => {
    // 清除之前可能存在的错误
    setErrors({});
    initLoginCredentials();
  }, []);

  // 初始化登录凭据
  const initLoginCredentials = () => {
    const {email,password} = getLastLoginCredentials()
    // 设置默认值
    setEmail(email);
    setPassword(password);
  }

  // 邮箱输入处理
  const handleEmailChange = (text: string) => {
    setEmail(text);
    // 实时验证：如果之前有错误，则在输入时就验证
    if (errors.email) {
      validateField("email", text, validateEmail);
    }
  };

  // 密码输入处理
  const handlePasswordChange = (text: string) => {
    setPassword(text);
    // 实时验证：如果之前有错误，则在输入时就验证
    if (errors.password) {
      validateField("password", text, validatePassword);
    }
  };

  // 登录处理
  const handleLogin = async () => {
    Keyboard.dismiss();

    const isEmailValid = validateField("email", email, validateEmail);
    const isPasswordValid = validateField(
      "password",
      password,
      validatePassword
    );

    if (!isEmailValid || !isPasswordValid) {
      console.log("Validation failed - not proceeding with login");
      return;
    }

    // 协议检查
    if (!agreed) {
      Alert.alert("提示", "继续登录表示已阅读并同意用户协议", [
        { text: "取消", style: "cancel" },
        {
          text: "确定",
          onPress: async () => {
            setAgreed(true);
            await toLogin();
          },
        },
      ]);
      return;
    }
    await toLogin();
  };

  // 执行登录逻辑
  const toLogin = async () => {
    const result = await loginWithEmailPassword(email, password);

    if (result.success) {
      showAlert("success", "登陆成功");
      router.replace("/");
    } else {
      showAlert("error", `登陆失败:${result.message}`);
    }
  };

  return (
    <LoginContainer title="邮箱密码登录" subtitle="使用已经注册邮箱登录">
      {/* 邮箱输入 */}
      <FormInput
        value={email}
        onChangeText={handleEmailChange}
        placeholder="请输入注册邮箱"
        keyboardType="email-address"
        error={errors.email}
        onBlur={() => {
          console.log("Email blur - validating:", email);
          validateField("email", email, validateEmail);
        }}
      />

      {/* 密码输入 */}
      <FormInput
        value={password}
        onChangeText={handlePasswordChange}
        placeholder="请输入密码"
        secureTextEntry={!showPassword}
        toggleSecureEntry={() => setShowPassword(!showPassword)}
        error={errors.password}
        onBlur={() => {
          console.log("Password blur - validating:", password);
          validateField("password", password, validatePassword);
        }}
      />

      {/* 协议同意 */}
      <AgreementCheck agreed={agreed} setAgreed={setAgreed} />

      {/* 登录按钮 */}
      <FormButton title="登录" onPress={handleLogin} isLoading={isLoading} />
    </LoginContainer>
  );
};

export default EmailLoginByPassword;
